package com.jf.concurrent.queue.demo;

import cn.hutool.core.thread.ExecutorBuilder;
import cn.hutool.core.thread.ThreadFactoryBuilder;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static java.lang.System.out;
import static java.lang.Thread.currentThread;

/**
 * 控制器
 *
 * @author Junfeng
 */
public class Controller {

    public static volatile boolean FLAG = true;

    public static void main(String[] arg) throws InterruptedException {

        Topic topic = new Topic("Topic-JF", new ArrayBlockingQueue<String>(10));

        ThreadPoolExecutor pPool = ExecutorBuilder.create()
                .setCorePoolSize(3)
                .setMaxPoolSize(10)
                .setKeepAliveTime(3, TimeUnit.SECONDS)
                .setWorkQueue(new ArrayBlockingQueue<>(5))
                .setHandler(new ThreadPoolExecutor.AbortPolicy())
                .setThreadFactory(ThreadFactoryBuilder.create().setNamePrefix("PRODUCE - ").build())
                .build();

        for (int i = 0; i < 1; i++) {
            pPool.submit(new Producer(topic));
        }

        ThreadPoolExecutor cPool = ExecutorBuilder.create()
                .setCorePoolSize(3)
                .setMaxPoolSize(10)
                .setKeepAliveTime(3, TimeUnit.SECONDS)
                .setWorkQueue(new ArrayBlockingQueue<>(5))
                .setHandler(new ThreadPoolExecutor.AbortPolicy())
                .setThreadFactory(ThreadFactoryBuilder.create().setNamePrefix("CONSUME - ").build())
                .build();

        for (int i = 0; i < 2; i++) {
            cPool.submit(new Consumer(topic));
        }


        TimeUnit.SECONDS.sleep(5);
        FLAG = false;
        out.println(currentThread().getName() + "\t FLAG=" + FLAG);
        out.println();
        out.println();

        pPool.shutdown();
        cPool.shutdown();

    }

}
